<?php
	//fil d'ariane
	$ariane = array(
		array(
			'href' => "index.php",
			'name' => "Home"
		),
		array(
			'href' => "submit.php",
			'name' => "Submit record"
		)
	);
	
	require("include/includes.php");
	require("include/getIP.php");
	/*
	if(isset($_GET['mobile']))
	{
		$_POST['mobile'] = $_GET['mobile'];
		$_POST['login'] = $_GET['login'];
		$_POST['password'] = $_GET['password'];
	}*/
	
	$oldRecord = null;
	$mobile = false;
	if (!isset($_SESSION['user']) && isset($_POST['mobile']) && isset($_POST['login']) && isset($_POST['password']))
	{
		$mobile=true;
	}
	else if(!isset($_SESSION['user'])) //TODO ne pas faire cette vérif ici??
	{
		die( 'NOT LOGGED' );
		echo( 'NOT LOGGED' );
	}
	
	// Champs obligatoires ('nom du champ' => 'nom affiché lors d'une erreur')
	$requieredFields = Array(
		'track' => 'Track', 
		'type' => 'Type', 
		'mode' => 'Mode', 
		'version' => 'Version',
		'driver' => 'Driver',
		'minute' => 'Minute',
		'second' => 'Second',
		'hundredth' => 'Hundredth');
	
	// Valeurs initiales
	$valueTrack 		= postOrCustom('track', '');
	$valueType		  	= postOrCustom('type', COURSE);
	$valueMode		  	= postOrCustom('mode', CLASSIC);
	$valueVersion	  	= postOrCustom('version', PAL);
	$valueDriver  		= postOrCustom('driver', '');
	$valueCheatStp		= postOrCustom('stp', '');
	$valueCheatIce		= postOrCustom('ice', '');
	$valueMinute	 	= postOrCustom('minute', 0);
	$valueSecond	 	= postOrCustom('second', 60);
	$valueHundredth	 	= postOrCustom('hundredth', 100);
	$valueProof		 	= postOrCustom('proof', '');
	$valueNeg		 	= postOrCustom('neg', false); // In Relic mode, the time can be negative
	$sign = ($valueNeg && $valueType==RELIC)? -1 : 1;
	$time = 59999;
	$errors = Array();
	$mobile_pid=false;
	
	$tracks = TrackName::getAll();
	$types = TrackType::getAll(true);
	$modes = TrackMode::getAll();
	$versions = Version::getAll();
	$drivers = Character::getAll();
	
	/// --- VALIDATION DU FORMULAIRE ---
	if(isset($_POST['submit']) || $mobile)
	{ //$errors[] = 'post detected';
		if($mobile)
		{
			$mobile_pid=Player::checkLogin($_POST['login'], $_POST['password']);
			//echo '$mobile_pid=Player::checkLogin($_POST[login], $_POST[password]): '.var_dump($mobile_pid)."=Player::checkLogin($_POST[login], $_POST[password])";
			if($mobile_pid===false)
			{
				$errors['badLogin'] = 'Invalid login or password';
			}
		}
		else
		{
			if(!verifyCsrfToken())
			{
				$errors['csrf'] = 'Security token missing!';
			}
		}
		
		if(empty($errors)) // CSRF ok OR Mobile connexion ok
		{
			// vérification des champs obligatoires
			foreach($requieredFields as $reqField => $reqText)
			{
				if(!isset($_POST[$reqField]) || empty($_POST[$reqField]))
				{
					if($_POST[$reqField] !== '0') // pas d'erreur si c'est le chiffre zero
						$errors[$reqField] = 'Please fill the field "'.$reqText.'"';
				}
			}
			
			// Proof = URL valide?
			if(!empty($valueProof) && !urlIsValid($valueProof))
			{
				$errors['proof'] = 'The proof is not a valid link (http://...)';
			}
		}
		// Traitement des données (si aucune erreur)
		if(empty($errors))
		{
			$ok = true;
			if(!empty($valueProof))
			{
				if(substr($valueProof, 0, 19) == 'http://www.youtube.')
				{
					$valueProof = str_replace("watch?v=", "embed/", $valueProof);
					$valueProof = explode('&', $valueProof);
					$valueProof = $valueProof[0];
				}
				
				$newProof = new Proof(Array('url' => $valueProof));
				$ok = $newProof->save(); 
				if(!$ok)//erreurs lors du save
				{
					$errors['proof'] = 'Invalid proof link, or intern error';
				}
			}
			if($ok)
			{
				$newRecord = new Record(Array(
					'player_id' => isset($_SESSION['user'])? $_SESSION['user']->getId() : $mobile_pid,
					'track_name_id' => $valueTrack,
					'track_mode_id' => $valueMode,
					'track_type_id' => $valueType,
					'character_id' => $valueDriver,
					'version_id' => $valueVersion,
					'ip' => getIP(),
					'proof_id' => isset($newProof)? $newProof->getId() : NULL,
					'time' => $sign * Record::MSHToTime($valueMinute, $valueSecond, $valueHundredth),
					'penta' => ($valueDriver==PENTA),
					'stp' => !empty($valueCheatStp),
					'ice' => !empty($valueCheatIce),
					'state' => OK
				));
				$newRecord->computeRank(-1, $valueTrack);
				
				// STATE: condition de nécessité de validation par un modo
				if($newRecord->getRank() <= 3) // top3
				{
					if(empty($valueProof))
					{
						$errors['proof'] = 'Top 3 record, you must give a proof (your record will be valided by a moderator)';
						$ok = false;
					}
					else
					{
						$newRecord->setState(PENDING);
					}
				}
				
				if($ok)
				{
					// On récupère l'ancien record, s'il y en a un.
					$oldRecord = $newRecord->getOldRecord();
					if($oldRecord)
					{
						$oldRecord->computeRank(-1, $valueTrack);
						//var_dump($oldRecord);
					}
					
					$ok = $newRecord->save();
					if(!$ok)
					{
						//TODO si erreur il faut deleter la proof
						$errors[] = 'Error while saving record';
					}
					else
					{
						if($oldRecord)
						{
							$oldRecord->delete();
						}
						
						// Compute Combined //TODO: manage state=3 (pending)
						if($valueType==COURSE || $valueType==LAP){
							if($valueType==COURSE){
								$correspondingRecord = $newRecord->getCorrespondingRecord(LAP);
							}elseif ($valueType==LAP){
								$correspondingRecord = $newRecord->getCorrespondingRecord(COURSE);
							}
							
							// if we can make combined time (course+lap)
							if(!is_null($correspondingRecord)){
								$newCombinedRecord = $newRecord->copy();
								$newCombinedRecord->setTrackTypeId(COMBINED1);
								// retreive old combined, if any
								$oldCombinedRecord = $newCombinedRecord->getOldRecord();
								if(!is_null($oldCombinedRecord)){
									$newCombinedRecord = $oldCombinedRecord;
								}
								// set and save the new one
								$newCombinedRecord->setTime($newRecord->getTime() + $correspondingRecord->getTime());
								$newCombinedRecord->computeRank(-1, $valueTrack);
								$newCombinedRecord->save();
							}
						}
						
						
					} // end if(ok) [$newRecord->save()]
				} // end if(ok) [top3 && proof]
			} // end if(ok) [$newProof->save()]
			if($ok)
			{
				$newRecordsHistory = new RecordsHistory(Array(
					'player_id' => isset($_SESSION['user'])? $_SESSION['user']->getId() : $mobile_pid,
					'track_name_id' => $valueTrack,
					'track_mode_id' => $valueMode,
					'track_type_id' => $valueType,
					'version_id' => $valueVersion,
					'ip' => getIP(),
					'proof_id' => isset($newProof)? $newProof->getId() : NULL,
					'time' => $sign * Record::MSHToTime($valueMinute, $valueSecond, $valueHundredth),
					'action' => 1,
					'rank' => $newRecord->getRank(),
					'moderator_id' => NULL
				));
				
				$newRecordsHistory->save(); // Si erreur pour le RecordsHistory, c'est pas "grave": on ignore.
			} // end if(ok)
		}
	}
	if($mobile)
	{
		if(!empty($errors))
		{
			echo '1';
			foreach($errors as $error)
			{
				echo $error."\n";
			}
		}
		else
		{
			echo '0';
			echo "Your time $valueMinute:$valueSecond:$valueHundredth has been added to ctr4ever";
		}
	}
	else // not from the mobile app
	{
		if(!empty($errors) ||!isset($_POST['submit']))
		{
			$template = $twig->loadTemplate('submit.html');
			$template->display(array(
				'pageTitle' 		=> 'ctr4ever - Submit your times',
				'tracks' 			=> $tracks,
				'types' 			=> $types,
				'modes' 			=> $modes,
				'versions' 			=> $versions,
				'drivers' 			=> $drivers,
				'valueTrack'		=> $valueTrack,
				'valueType'			=> $valueType,
				'valueMode'			=> $valueMode,
				'valueVersion'		=> $valueVersion,
				'valueDriver'		=> $valueDriver,
				'valueCheatStp'		=> $valueCheatStp,
				'valueCheatIce'		=> $valueCheatIce,
				'valueMinute'		=> $valueMinute,
				'valueSecond'		=> $valueSecond,
				'valueHundredth'	=> $valueHundredth,
				'valueProof'		=> $valueProof,
				'valueNeg'			=> $valueNeg,
				'errors'			=> $errors
			));
		}
		else
		{
			echo "Your time $valueMinute:$valueSecond:$valueHundredth has been added to ctr4ever";
			if($oldRecord)
			{
				$dRank = $oldRecord->getRank() - $newRecord->getRank();
				$class = 'positive';
				$sign  = '+';
				if($dRank<0)
				{
					$class = 'negative';
					$sign  = ''; // already a '-'
				}
				echo '<br />Old record: '.$oldRecord. ' (rank:'. $oldRecord->getRank(). ') (standard: '.$oldRecord->getStandard().')<br />';
				echo '      New record: '.$newRecord. ' (rank:'. $newRecord->getRank(). ' [<span class="'.$class.'">'.$sign.$dRank.'</span>]) (standard: '.$newRecord->getStandard().')<br />';
			}
			//var_dump($newRecordsHistory);
		}
	}
?>